package com.exam.api.common;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

public class StringToJsonSerializer extends JsonSerializer<String> {


    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        ObjectMapper mapper = SpringUtil.getBean(ObjectMapper.class);
        try {
            if (StrUtil.isEmpty(value)) {
                gen.writeObject(mapper.readTree(StrUtil.EMPTY_JSON));
            } else {
                //如果是json，则返回解析后的json
                if (JSONUtil.isTypeJSON(value)) {
                    gen.writeObject(mapper.readTree(value));
                } else {
                    gen.writeObject(value);
                }
            }
        } catch (Exception e) {
            gen.writeObject(value);
        }
    }
}
